<template>
     <div class="rightBoxContainer">
          <div class="titleBox">
               <span v-if="chartData?.province">
                    {{ chartData?.province + ' ' + chartData?.city + ' ' + chartData?.conty + ' ' + chartData?.village }}
               </span>
               <span v-else>请选择行政区划</span>
          </div>
          <div class="searchBox">
               <page-search
                    pageName="pages_container"
                    v-if="searchFormConfigRef"
                    ref="pageSearchRef"
                    :searchConfig="searchFormConfigRef"
                    @queryBtnClick="handleQueryClick"
                    @resetBtnClick="handleResetClick"
                    @searchChange="searchChange">
                    <template #button></template>
               </page-search>
          </div>
          <div class="tableBox">
               <page-content
                    v-if="contentTableConfigRef"
                    ref="pageContentRef"
                    :tableLoading="tableLoading"
                    pageName="pages_container"
                    :contentConfig="contentTableConfigRef"
                    @getTableList="getTableList"
                    @editBtnClick="handleEditData"
                    @delBtnClick="handleDelData"
                    @getSelectionData="getSelectionData"
                    :deleteBtnShow="false"
                    :editBtnShow="true"
                    :showHandle="true">
                    <template #btns>
                         <div v-if="isHiddenMangeShow">
                              <el-button @click="handleNewData()" type="primary">新增</el-button>
                              <el-button type="primary" @click="batchDistributed()">批量派发</el-button>
                              <el-button type="primary" @click="exportExcel()">导出EXCEL</el-button>
                              <el-button type="primary" @click="downLoadTemplate()">模板下载</el-button>
                              <uploadBtn @onSuccess="handleUploadClick" text="批量录入" type="primary"></uploadBtn>
                         </div>
                    </template>
                    <template #startlc="scoped">
                         {{ scoped.row.startlc ? parseMileage(scoped.row.startlc) : '-' }}
                    </template>
                    <template #endlc="scoped">
                         {{ scoped.row.endlc ? parseMileage(scoped.row.endlc) : '-' }}
                    </template>
                    <template #createtime="scoped">
                         {{ scoped.row.createtime ? formatDate(scoped.row.createtime) : '-' }}
                    </template>
                    <template #repairbefore="scoped">
                         <el-image
                              v-if="scoped.row.repairbefore"
                              style="width: 100px; height: 30px"
                              :src="urlFun(scoped.row.repairbefore)"
                              :zoom-rate="1.2"
                              :max-scale="7"
                              :min-scale="0.2"
                              preview-teleported
                              :preview-src-list="[urlFun(scoped.row.repairbefore)]"
                              fit="cover" />
                    </template>
                    <template #repairafter="scoped">
                         <el-image
                              v-if="scoped.row.repairafter"
                              style="width: 100px; height: 30px"
                              :src="urlFun(scoped.row.repairafter)"
                              :zoom-rate="1.2"
                              :max-scale="7"
                              :min-scale="0.2"
                              preview-teleported
                              :preview-src-list="[urlFun(scoped.row.repairafter)]"
                              fit="cover" />
                    </template>
                    <template #distributed="scoped">
                         <el-button v-if="isHiddenMangeShow" type="primary" size="small" title="派发" @click="batchDistributed(scoped.row)">
                              <i class="iconfont icon-feixingmanyou"></i>
                         </el-button>
                    </template>
                    <template #xiaohao="scoped">
                         <span v-if="scoped.row.xiaohaostatus == '未销号' && isHiddenMangeShow">
                              <el-button type="warning" size="small" title="销号" @click="xiaohaoBtn(scoped.row)">
                                   <i class="iconfont icon-shenqingxiaohao"></i>
                              </el-button>
                         </span>
                    </template>
               </page-content>
          </div>
          <page-modal
               v-if="modalConfigRef && modalConfigRefShow"
               ref="pageModalRef"
               :modalConfig="modalConfigRef"
               :defaultInfo="modalInfo"
               pageName="pages_container"
               @addSuccess="addSuccess"
               @editSuccess="editSuccess"></page-modal>
          <page-modal
               v-if="distributedModalConfigRef"
               ref="distributedmodalRef"
               :modalConfig="distributedModalConfigRef"
               :defaultInfo="distributedModalInfo"
               pageName="pages_container"
               @addSuccess="distributedSubmit"></page-modal>
          <el-dialog v-model="xiaohaoDialog" title="修改销号状态" width="800">
               <el-form ref="xiaohaoFormRef" :model="xiaohaoForm" :rules="xiaohaoFormRules" label-width="auto" status-icon>
                    <el-form-item label="整改前照片 :" prop="beforeRectification">
                         <uploadBtn
                              @onSuccess="beforeRectificationSuccess"
                              :showFileList="true"
                              :fileType="['.jpg', '.png']"
                              text="请上传整改前照片"
                              type="primary"
                              list-type="picture"
                              width="100%"></uploadBtn>
                    </el-form-item>
                    <el-form-item label="整改后照片 :" prop="afterRectification">
                         <uploadBtn
                              @onSuccess="afterRectificationSuccess"
                              :showFileList="true"
                              :fileType="['.jpg', '.png']"
                              text="请上传整改后照片"
                              type="primary"
                              list-type="picture"
                              width="100%"></uploadBtn>
                    </el-form-item>
                    <el-form-item label="销号说明 :" prop="explain">
                         <el-input type="textarea" v-model="xiaohaoForm.explain" :rows="3"></el-input>
                    </el-form-item>
               </el-form>
               <template #footer>
                    <div class="dialog-footer">
                         <el-button type="primary" @click="xiaohaoSubmit">确定</el-button>
                         <el-button @click="xiaohaoDialog = false">取消</el-button>
                    </div>
               </template>
          </el-dialog>
     </div>
</template>

<script setup lang="ts">
import pageContent from '@/components/pageContent'
import pageSearch from '@/components/pageSearch'
import pageModal from '@/components/pageModal'
import { usePageTable } from '@/hooks/table/usePageTable'
import { contentTableConfig, emptyTableConfig } from './config/content.config'
import { searchFormConfig } from './config/search.config'
import { modalConfig, distributedModalConfig } from './config/modal.config'
import uploadBtn from '@/components/uploadBtn/index.vue'
import {
     GetType,
     GetHazardPc,
     GetHazardPcExport,
     UpdateHazardBatch,
     ExportTemplateData,
     UpdateHazard,
     UpdateHazardFile,
     SaveAllHazardData,
     CreateHazard,
} from '@/api/hiddenDangerRecords'
import { GetDistrictsByLevelAndName, GetLineList } from '@/api/common'
import { ElMessage } from 'element-plus'
import { formatDate, parseMileage } from '@/utils/formtFun'
import { download } from '@/utils/exportFile'
import useUserStore from '@/store/modules/user'

let useStore = useUserStore()
let props = defineProps({
     chartData: {
          type: Object as PropType<any>,
     },
})
// 单个删除方法回调
const delHandleCallback = async (val: any) => {
     try {
          // let obj = {
          //      ids: val ?? modalInfo.value.id,
          // }
          // const { code } = await DeleteMeet(obj)
          // const message = code == 200 ? '删除成功' : '删除失败'
          // ElMessage({ type: code == 200 ? 'success' : 'error', message })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}
const modalConfigRefShow = ref(true)
const editHandleCallback = async (val: any) => {
     let district = [val.province, val.city, val.conty, val.village]
     // 从后往前循环判断 省市县镇是否为空
     for (let i = district.length - 1; i >= 0; i--) {
          if (district[i]) {
               break
          }
          district.pop()
     }
     modalInfo.value = {
          ...val,
          district: district[district.length - 1] ?? '',
     }
     console.log('modalInfo.value', modalInfo.value)
     modalConfigRefShow.value = false
     nextTick(() => {
          modalConfigRefShow.value = true
     })
     modalConfigRefShow.value = true
}
const {
     searchFormConfigRef,
     contentTableConfigRef,
     modalConfigRef,
     pageModalRef,
     pageContentRef,
     pageSearchRef,
     modalInfo,
     tableLoading,
     selectCheckData,
     permissionRef,
     handleOnSuccess,
     handleNewData,
     handleEditData,
     handleDelData,
     handleQueryClick,
     handleResetClick,
     getSelectionData,
     templateDownloadClick,
     hasPermission,
} = usePageTable(null, editHandleCallback, null, delHandleCallback)

const distributedModalConfigRef = ref(distributedModalConfig)
const distributedmodalRef = ref<any>(null)
const distributedModalInfo = ref({})
onMounted(async () => {
     console.log('props.chartData', props.chartData)
     await getSelectOptions()
     contentTableConfigRef.value = contentTableConfig
     searchFormConfigRef.value = searchFormConfig
     modalConfigRef.value = modalConfig
     await nextTick(() => {
          pageSearchRef.value?.handleResetClick()
     })
})
const searchChange = (data: any) => {
     console.log('searchChange', data)
}
const userPermission = computed(() => {
     return useStore.userInfoData.permission?.split(',') ?? []
})
// const isUserMangeShow = computed(() => {
//      return userPermission.value.includes('用户管理') ?? false
// })

const isHiddenMangeShow = computed((): boolean => {
     return userPermission.value.includes('隐患管理') ?? false
})
const getTableList = async (params: any, isExport: boolean = false) => {
     try {
          const requestParams = {
               ...params,
               ...props.chartData,
               isExport: isExport,
          }
          tableLoading.value = true
          const tabelData: any = await GetHazardPc(requestParams)
          tableLoading.value = false
          const newData = tabelData.Data || []
          const newTotal = Number(tabelData.Count) || 0
          nextTick(() => {
               if (newData.length > 0) {
                    pageContentRef.value!.setTableData(newData, newTotal)
               } else {
                    pageContentRef.value!.setTableData([], 0)
               }
          })
     } catch (error) {
          tableLoading.value = false
          console.error('Failed to get table data:', error)
     }
}

const findPathToNode = (tree: any[], targetLabel: string, currentPath: any[] = []): any[] | null => {
     for (const node of tree) {
          if (!node.Name) {
               continue // 跳过空标签的节点
          }
          const newPath = [...currentPath, node]
          if (node.Name === targetLabel) {
               return newPath
          }
          if (node.SubDistricts && node.SubDistricts.length > 0) {
               const result = findPathToNode(node.SubDistricts, targetLabel, newPath)
               if (result) {
                    return result
               }
          }
     }
     return null
}
const dislevel = ref('')
const formatAddAndEditData = (data: any) => {
     let activeData = Array.isArray(data.district) ? data.district[data.district.length - 1] : data.district
     let path: any = findPathToNode(districtList.value, activeData)
     dislevel.value = path[path.length - 1].Unit ?? ''
     let district = {
          province: '',
          city: '',
          conty: '',
          village: '',
     }
     if (path) {
          path.forEach((node: any) => {
               switch (node.Unit) {
                    case '省':
                         district.province = node.Name
                         break
                    case '市':
                         district.city = node.Name
                         break
                    case '县':
                         district.conty = node.Name
                         break
                    case '乡':
                         district.village = node.Name
                         break
                    default:
                         break
               }
          })
     }
     return {
          ...data,
          ...district,
     }
}
// 新增的回调方法
const addSuccess = async (val: any) => {
     try {
          let obj = {
               ...formatAddAndEditData(val),
          }
          delete obj.district
          const res: any = await CreateHazard(obj)
          const message = res == '添加成功' ? '添加成功' : '添加失败'
          ElMessage({
               type: res == '添加成功' ? 'success' : 'error',
               message,
          })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}

// 编辑的回调方法
const editSuccess = async (val: any) => {
     try {
          let obj = {
               ...val,
          }
          const res: any = await UpdateHazard(obj)
          const message = res == '修改成功' ? '编辑成功' : '编辑失败'
          ElMessage({
               type: res == '修改成功' ? 'success' : 'error',
               message,
          })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}
// 获取对应选择器的下拉选项
const districtList = ref([])
const getSelectOptions = async () => {
     try {
          const res: any = await GetType()
          const res1: any = await GetLineList()
          const res2: any = await GetDistrictsByLevelAndName()
          const options = res.map((item: any) => ({
               label: item.yhtype,
               value: item.yhtype,
          }))
          searchFormConfig.formItems.forEach((item) => {
               if (item.field === 'yhtype') {
                    item.options = options
               }
          })
          modalConfig.formItems.forEach((item: any) => {
               if (item.field === 'yhtype') {
                    item.options = options
               } else if (item.field === 'xlname' && res1 && Array.isArray(res1)) {
                    item.options = res1.map((item: any) => {
                         return {
                              label: item.xlname,
                              value: item.xlname,
                         }
                    })
               } else if (item.field === 'district') {
                    item.cascader = Array.isArray(res2) ? res2 : []
                    districtList.value = item.cascader
               }
          })
     } catch (error) {
          console.error('Error fetching select options:', error)
     }
}
watch(
     () => props.chartData,
     () => {
          pageSearchRef.value?.handleQueryClick()
     },
     { deep: true },
)
const activeYhid = ref('') // 隐患id
const batchDistributed = async (rowData: any = null) => {
     if (rowData) {
          activeYhid.value = rowData.yhid
          distributedmodalRef.value!.dialogVisible = true
          return
     }
     activeYhid.value = ''
     if (Array.isArray(selectCheckData.value) && !selectCheckData.value.length) {
          ElMessage({ type: 'warning', message: '请选择要分配的数据' })
          return
     }
     distributedmodalRef.value!.dialogVisible = true
}

const xiaohaoFormRef: any = ref(null)
const xiaohaoDialog = ref(false)
const xiaohaoFormRules = {
     beforeRectification: [{ required: true, message: '请上传整改前照片', trigger: 'blur' }],
     afterRectification: [{ required: true, message: '请上传整改后照片', trigger: 'blur' }],
     explain: [{ required: true, message: '请输入销号说明', trigger: 'blur' }],
}
const beforeRectificationSuccess = (val: any) => {
     xiaohaoForm.value.beforeRectification = val
}
const afterRectificationSuccess = (val: any) => {
     xiaohaoForm.value.afterRectification = val
}
const xiaohaoForm = ref({
     yhid: '',
     xiaohaostatus: '',
     beforeRectification: '',
     afterRectification: '',
     address: '',
     dislevel: '',
     explain: '',
})
const urlFun = (url: any) => {
     // 获取当前环境变量
     const env = import.meta.env.VITE_SERVE
     return url ? env + url?.split('~')[1] : ''
}
const xiaohaoBtn = async (val: any) => {
     xiaohaoDialog.value = true
     xiaohaoForm.value.yhid = val.yhid
     xiaohaoForm.value.xiaohaostatus = '已销号'
     nextTick(() => {
          xiaohaoFormRef.value && xiaohaoFormRef.value.resetFields()
     })
}
const xiaohaoSubmit = () => {
     xiaohaoFormRef.value &&
          xiaohaoFormRef.value.validate(async (valid: any) => {
               if (valid) {
                    try {
                         let obj = {
                              yhid: xiaohaoForm.value.yhid,
                              xiaohaostatus: xiaohaoForm.value.xiaohaostatus,
                              address: xiaohaoForm.value.address,
                              dislevel: xiaohaoForm.value.dislevel,
                              explain: xiaohaoForm.value.explain,
                         }
                         const filelist = [...xiaohaoForm.value.beforeRectification, ...xiaohaoForm.value.afterRectification]
                         const res: any = await UpdateHazardFile(obj, filelist)
                         if (res && res == '销号成功') {
                              ElMessage({
                                   type: 'success',
                                   message: '销号成功',
                              })
                              pageSearchRef.value?.handleQueryClick()
                         } else {
                              ElMessage({
                                   type: 'error',
                                   message: '销号失败',
                              })
                         }
                    } catch (error) {
                         console.log(error)
                    } finally {
                         xiaohaoDialog.value = false
                    }
               } else {
                    console.log('error submit!!')
               }
          })
}
const exportExcel = async () => {
     // const ids = selectCheckData.value.map((item: any) => item.id)
     try {
          let obj = {
               ...pageSearchRef.value.filterFormData,
               ...props.chartData,
               ...pageContentRef.value!.pageInfo,
               // ids: ids.join(','),
               isExport: true,
          }
          const res = await GetHazardPcExport(obj)
          download(res, 'excels', `隐患数据_${new Date().toLocaleDateString()}.xlsx`)
          ElMessage.success('导出成功')
     } catch (error) {
          console.log(error)
     }
}

// 批量录入
const handleUploadClick = async (fileList: any) => {
     try {
          let obj = {}
          const res: any = await SaveAllHazardData(obj, fileList)
          const message = res == '数据保存成功！' ? '上传成功' : '上传失败'
          ElMessage({
               type: res == '数据保存成功！' ? 'success' : 'error',
               message,
          })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}
const downLoadTemplate = () => {
     ExportTemplateData().then((res) => {
          download(res, 'excels', `隐患导入模板_${new Date().toLocaleDateString()}.xlsx`)
     })
}
const distributedSubmit = async (val: any) => {
     try {
          let obj = []
          if (activeYhid.value) {
               obj = [
                    {
                         Yhid: activeYhid.value,
                         Dislevel: val.distributedStatus,
                    },
               ]
          } else {
               obj = selectCheckData.value.map((item: any) => {
                    return {
                         Yhid: item.yhid,
                         Dislevel: val.distributedStatus,
                    }
               })
          }
          const res: any = await UpdateHazardBatch(obj)
          if (res == '批量修改成功') {
               ElMessage({ type: 'success', message: '修改成功' })
               pageSearchRef.value?.handleQueryClick()
          } else {
               ElMessage({ type: 'error', message: '修改失败' })
          }
     } catch (error) {
          console.log(error)
     }
}
</script>

<style lang="scss" scoped>
.rightBoxContainer {
     width: 100%;
     height: 100%;
     display: flex;
     flex-direction: column;
     overflow: auto;
     padding-right: 5px;

     .titleBox {
          width: 100%;
          height: 5%;
          color: #fff;
          font-weight: bold;
          font-size: 18px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #0a3e6e;
          border-radius: 5px;
     }

     .searchBox {
          width: 100%;
          height: auto;
     }

     .tableBox {
          height: 80%;
          width: 100%;
          border-radius: 10px;
     }
}
</style>
